package br.edu.unilasalle.simon_api.rs;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;

import br.edu.unilasalle.simon_api.domain.Venda;
import br.edu.unilasalle.simon_api.service.IVendaService;

@Path("/venda")
public class VendaRS {
	
	@Autowired
	private IVendaService service;
	
	private static final SimpleDateFormat SDF1 = new SimpleDateFormat("yyyy-MM-dd");
	private static final SimpleDateFormat SDF2 = new SimpleDateFormat("dd/MM/yyyy");
	
	@GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Venda> findAllByPeriodo(@QueryParam("dataIni") String dataIni, @QueryParam("dataFim") String dataFim) {
		Date dtIni = null;
		Date dtFim = null;
		try {
			dtIni = SDF1.parse(dataIni);
			dtFim = SDF1.parse(dataFim);
		} catch (ParseException e1) {
			try {
				dtIni = SDF2.parse(dataIni);
				dtFim = SDF2.parse(dataFim);
			} catch (ParseException e2) {
				e2.printStackTrace();
			}
		}
		if (dtIni != null && dtFim != null) {
			return service.findAllByPeriodo(dtIni, dtFim);
		} else {
			return null;
		}
    }
	
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Venda create(Venda obj) {
        return service.save(obj);
    }

}
